package com.shujia.wyh.udtfdemos;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

/**
 * 进入的一行：   a,1,2,3,4,5,6,7,8,9,10,11,12
 * 出来的是：
 * a  0时  1
 * a  2时  2
 * a  4时  3
 * ...
 */
public class MyUDTFDemo2 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建集合,将来存储列构造器（列名）
        ArrayList<String> filedNames = new ArrayList<String>();
        //列的类型
        ArrayList<ObjectInspector> filedObj = new ArrayList<ObjectInspector>();

        filedNames.add("id");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("hour");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("value");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, filedObj);
    }

    @Override
    public void process(Object[] args) throws HiveException {
        //a,1,2,3,4,5,6,7,8,9,10,11,12
        String id = args[0].toString();
        int hour = 0;
        String[] strs = new String[3];
        strs[0] = id;
        //从第2个元素开始遍历，得到每一次检测的值
        for (int i = 1; i < args.length; i++) {
            String value = args[i].toString();
            strs[1] = hour + "时";
            strs[2] = value;
            hour += 2;
            forward(strs);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
